package com.lz.blog.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lz.blog.dao.pojo.SysUser;
import com.lz.blog.service.LoginService;
import com.lz.blog.utils.UserThreadLocal;
import com.lz.blog.vo.ErrorCode;
import com.lz.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器，用于拦截需登录才能访问的接口
 *
 * @author Liz
 * @date 2023/02/14 15:47
 **/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行Controller方法（handler）之前进行调用
        /**
         * 1、需要判断请求的接口的路径 是否是需要进行登录
         * 2、判断token是否为空，如果为空，则未登录
         * 3、如果不为空，进行验证 checkToken（）
         * 4、验证成功进行跳转
         */
        if (!(handler instanceof HandlerMethod)) {
            //handler 可能是 访问资源处理器，直接放行
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (ObjectUtil.isEmpty(token)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //认证token是否正确
        SysUser sysUser = loginService.checkToken(token);
        if (ObjectUtil.isEmpty(sysUser)) {
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
        }
        //登陆验证成功
        //如果希望直接在Controller处理器中使用该user，那么可以将信息放入ThreadLocal中
        UserThreadLocal.put(sysUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //不删除会有内存泄漏风险
        UserThreadLocal.remove();
    }
}
